package com.zjp.blog.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjp.blog.data.client.TagMapper;
import com.zjp.blog.controller.PagerBean;
import com.zjp.blog.data.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */
@Service
public class TagService
{
    @Autowired
    TagMapper tagMapper;

    public PagerBean<Tag> getPage(PagerBean<Tag> pager)
    {
        PageHelper.startPage(pager.getPageNum(),pager.getLength());
        List<Tag> tags = tagMapper.selectAll();

        PageInfo pageInfo = new PageInfo(tags);

        pager.setPages(pageInfo.getPages());
        pager.setRecords(tags);

        return pager;
    }

    public PagerBean<Tag> getPage(String name, PagerBean<Tag> pager)
    {
        PageHelper.startPage(pager.getPageNum(),pager.getLength());
        List<Tag> tags = searchByName(name);

        PageInfo pageInfo = new PageInfo(tags);

        pager.setPages(pageInfo.getPages());
        pager.setRecords(tags);

        return pager;
    }

    public int Create(Tag tag)
    {
        tag.setCreateTime(new Date());
        tag.setUpdateTime(tag.getCreateTime());

        return tagMapper.insertSelective(tag);
    }

    public int Update(Tag tag)
    {
        tag.setUpdateTime(new Date());
        return tagMapper.updateByPrimaryKeySelective(tag);
    }

    public Tag getById(Integer id)
    {
        return tagMapper.selectByPrimaryKey(id);
    }

    public List<Tag> getByIds(List<Integer> tagIds)
    {
        List<Tag> tags = null;

        if(tagIds!=null && !tagIds.isEmpty()){
            tags = tagMapper.selectByIds(tagIds);
        }

        return tags;
    }

    public List<Tag> searchByName(String name) {
        name = "%" + name + "%";
        return tagMapper.searchByName(name);
    }

    public Tag getByName(String name)
    {
        return tagMapper.selectByName(name);
    }

    public List<Tag> getByPostId(Integer id)
    {
        return tagMapper.selectByPostId(id);
    }

    public List<Tag> getAll() {
        return  tagMapper.selectAll();
    }

    public int deleteById(Integer id) { return tagMapper.deleteByID(id); }

}
